package edu.cmu.aes.project2.security;

import java.io.IOException;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class AccessLogFilter implements Filter {

	private Logger accessLog;
	private FileHandler fh;
	
	public void destroy() {
		if(fh!=null)
			fh.close();
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;

		// Get the IP address of client machine.
		String ipAddress = request.getRemoteAddr();
		String address = request.getRequestURI();

		// Log the IP address and current timestamp.
		String data = "IP " + ipAddress + ", Time "
				+ new Date().toString()+", request to "+address;
		if(accessLog != null)
			accessLog.log(Level.INFO, data);

		chain.doFilter(req, res);

	}

	public void init(FilterConfig arg0) throws ServletException {
		LogManager lm = LogManager.getLogManager();
		try {
			fh = new FileHandler("access_log.txt", true);
			fh.setFormatter(new SimpleFormatter());
			accessLog = Logger.getLogger(getClass().getName());
			lm.addLogger(accessLog);
			accessLog.setLevel(Level.INFO);			
			accessLog.addHandler(fh);
		} catch (SecurityException e) {
			e.printStackTrace();
			accessLog = null;
			fh = null;
		} catch (IOException e) {
			e.printStackTrace();
			accessLog = null;
			fh = null;
		}
		
	}

}
